﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace AppService {
    class Worker : MarshalByRefObject, IDisposable {
        private IDisposable p_Service;
        private Type p_ServiceType;
        
        public void Initialize(string type) {
            System.Threading.Thread.GetDomain().UnhandledException += new UnhandledExceptionEventHandler(Worker_UnhandledException);
            p_ServiceType = Type.GetType(type, true, false);
            p_Service = (IDisposable)Activator.CreateInstance(p_ServiceType);

            var @event = p_ServiceType.GetEvent("Exception");
            @event.AddEventHandler(p_Service, new System.Threading.ThreadExceptionEventHandler(p_Service_Exception));
        }

        void Worker_UnhandledException(object sender, UnhandledExceptionEventArgs e) {
            System.Diagnostics.EventLog.WriteEntry("AppService", "WorkerDomain_UnhandledException: " + e.ExceptionObject.ToString(), System.Diagnostics.EventLogEntryType.Error, 501);
        }

        public void Dispose() {
            try {
                if (p_Service != null) p_Service.Dispose();
            } catch (Exception ex) {
                System.Diagnostics.EventLog.WriteEntry("AppService", "Worker_DisposeException: " + ex.ToString(), System.Diagnostics.EventLogEntryType.Error, 502);
            } finally {
                p_Service = null;
            }
        }

        void p_Service_Exception(object sender, System.Threading.ThreadExceptionEventArgs e) {
            if (!(e.Exception is System.Threading.ThreadAbortException))
                System.Diagnostics.EventLog.WriteEntry("AppService", "Worker_UnhandledException: " + e.Exception.ToString(), System.Diagnostics.EventLogEntryType.Error, 500);
        }
    }
}
